package org.agilar.gwt.sortabletable;

public class PagedTableModel extends TableModel
{
	private int page = 0;
	private int pageSize = 0;
	private int pageCount = 0;
	private int totalRows = 0;
	private int sortColumn = -1;
	private boolean ascending = true;
	private Object [][] data;
	private boolean [] sortableFlag;
	
	private PagedTableModelSource source;
	
	public PagedTableModel(int columns, int pageSize, PagedTableModelSource source)
	{
		super(columns);
		this.data = new Object[0][columns];
		this.sortableFlag = new boolean[columns];
		for (int i=0; i<sortableFlag.length; i++)
		{
			sortableFlag[i] = true;
		}
		this.pageSize = pageSize;
		this.source = source;
	}
	
	@Override
	public Object get(int row, int column)
	{
		return data[row][column];
	}

	@Override
	public int getRowCount()
	{
		return data.length;
	}

	public int getPageCount()
	{
		return pageCount;
	}

	public int getPageSize()
	{
		return pageSize;
	}
	
	@Override
	public boolean isColumnSortable(int column)
	{
		return sortableFlag[column];
	}

	public void setColumnSortable(int column, boolean sortable)
	{
		sortableFlag[column] = sortable;
	}
	
	@Override
	public void sort(int column, boolean ascending)
	{
		this.sortColumn = column;
		this.ascending = ascending;
		source.getData(page, column, ascending, pageSize, this);
	}

	public int getPage()
	{
		return page;
	}
	
	public void setPage(int page)
	{
		source.getData(page, sortColumn, ascending, pageSize, this);
	}
	
	public void setPage(int page, boolean ascending)
	{
		source.getData(page, sortColumn, ascending, pageSize, this);
	}
	
	public void setData(int page, Object [][] data, int pageCount, int totalRows)
	{
		this.page = page;
		this.data = data;
		this.pageCount = pageCount;
		this.totalRows = totalRows;
		fireModelChanged();
	}

	public int getTotalRows()
	{
		return totalRows;
	}
}
